package com.example.mqproduct.producter;

import com.example.mqproduct.config.MqConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Component
public class Producer {

    private DefaultMQProducer producer;

    @PostConstruct
    void setProducter() {
        producer = new DefaultMQProducer();
        producer.setNamesrvAddr(MqConfig.nameServ);
        producer.setProducerGroup(MqConfig.group);
        //不开启vip通道 开通口端口会减2
        producer.setVipChannelEnabled(false);
        start();
    }

    private void start() {
        try {
            log.info("mq生产者启动...");
            this.producer.start();
            log.info("mq生产者启动完成...");
        } catch (MQClientException e) {
            log.info("mq启动异常: {}", e.getLocalizedMessage());
        }
    }

    public DefaultMQProducer getProducer() {
        return this.producer;
    }

    @PreDestroy
    void shutdown() {
        this.producer.shutdown();
    }

}
